#!/usr/bin/perl

use warnings;
use strict;

vienna();

sub vienna {
    
    #take input, one diagram per-line 
    while (<>) {        
        my %singleimage;
        my @in = split("\t",$_);
        foreach (@in) {
            my @a = split(" ",$_);
            my $key = shift(@a);
            my $value = join (" ",@a);
            $singleimage{$key}=$value if defined $key;
        }
        #print join ("\n", values %singleimage); #debug line
                
        open (DEFS, "<definitions.svg");
        while (<DEFS>) {
            $/="<";
            my $string = $_;
            
            if (!(/text/ or /path/)) {
                #next unless (/text/ or /path/);
            
            print $string;
                
            }
            
            elsif (/text/) {
                
                foreach my $k (sort(keys %singleimage)) {
                    
                    #lookup key value HERE;
                    if (/>$k</) {
                        my $toseektag=";opacity:0";
                        $string=~s/$toseektag/opacity:1/;
                    }                    
                }
                print $string;
            }
            
           
            
            elsif (/path/) {
                
                
                my %order;
                foreach my $o (keys %singleimage) { 
                    $order{$o}=length($o);
                }
                
                foreach my $k (sort { $order{$a} cmp $order{$b} } keys %order) {
                    
                    print STDERR $k,"\n";
                    
                    my $times = length($k);
                    #lookup key value HERE;
                    if (/[$k]{$times}/) {
                        my @colorvalue=split(" ",$singleimage{$k});
                        my $value = $colorvalue[-1];
                        #$value = $value/100;
                        my $toseektag="fill-opacity";
                        $string=~s/$toseektag:0\.\d{1,}/fill-opacity:$value/;
                    }                    
                }
                print $string;            }
        }
        close DEFS;

        exit;
    }
}
